package com.tao.mytestsocket

import android.Manifest
import android.content.Context
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.text.Editable
import android.text.TextWatcher
import android.view.Gravity
import android.widget.ScrollView
import androidx.appcompat.app.AppCompatActivity
import com.tao.mytestdd.datagrama.UDPSendManager
import com.tao.utils.ToastTools
import com.tao.utilslib.log.LogUtil
import com.tao.utilslib.log.logsave.LogSaveManager
import com.tao.utilslib.log.logsave.LogSaveType
import kotlinx.android.synthetic.main.activity_main.*
import java.lang.StringBuilder
import java.text.SimpleDateFormat
import java.util.*
import kotlin.concurrent.thread

class MainActivity : ILog, AppCompatActivity() {

    val httpTest = HttpTest(this)
    val udpTest = UDPTest(this)
    var logName = "test_log"

    companion object {
        var context: Context? = null
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        context = this
        http()
        udp()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), 100)
        }
        bt_clear.setOnClickListener {
            sb = StringBuilder()
            tv_text.text = sb.toString()
        }

        bt_big_data.setOnClickListener {
           ToastTools.showShort(this,"生成大数据中...",Gravity.CENTER)
           thread {
             val str =  crateBigData()
               runOnUiThread {
                   et_text_send.setText(str)
                   ToastTools.showShort(this,"数据设置完成.",Gravity.CENTER)

               }

           } 
        }

        thread {
            val ip = NetUtils.getLocalIPAddress().hostName
            runOnUiThread {
                localIP.text = "本机IP：$ip"
            }
        }
    }

    private fun crateBigData(): String {
        return UDPSendManager.createMsg(500*1024)
    }

    private fun udp() {
        try {
            udpTest.localPort = (et_port_UDP_local.text.toString().toInt())
        } catch (e: Exception) {
        }



        udpTest.serverIp = et_ip_udp.text.toString()
        try {
            udpTest.serverPort = et_port_udp.text.toString().toInt()
        } catch (e: Exception) {
        }


        //本地服务配置
        et_port_UDP_local.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                try {
                    udpTest.localPort = (et_port_UDP_local.text.toString().toInt())
                } catch (e: Exception) {
                }
            }

            override fun afterTextChanged(s: Editable?) {

            }
        })
        cb_local_udp.setOnCheckedChangeListener { _, it ->
            udpTest.switchHttp(it)
            renameLog()
        }

        // 远程服务配置
        et_ip_udp.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                udpTest.serverIp = et_ip_udp.text.toString()
            }

            override fun afterTextChanged(s: Editable?) {
            }
        })
        et_port_udp.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                try {
                    udpTest.serverPort = et_port_udp.text.toString().toInt()
                } catch (e: Exception) {
                }
            }

            override fun afterTextChanged(s: Editable?) {
            }
        })

        cb_udp_send_loop.setOnCheckedChangeListener { _, it -> udpTest.send_loop = it }
        bt_udp_send.setOnClickListener { udpTest.send(et_text_send.text.toString()) }

    }

    private fun renameLog() {
        logName =
            "test_log_${SimpleDateFormat("yyyy-MM-dd_hh_mm_ss").format(Date(System.currentTimeMillis()))}"
    }

    private fun http() {
        try {
            httpTest.localPort = (et_port_http_local.text.toString().toInt())
        } catch (e: Exception) {
        }

        httpTest.serverIp = et_ip_http.text.toString()
        try {
            httpTest.serverPort = et_port_http.text.toString().toInt()
        } catch (e: Exception) {
        }


        //本地服务配置
        et_port_http_local.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                try {
                    httpTest.localPort = (et_port_http_local.text.toString().toInt())
                } catch (e: Exception) {
                }
            }

            override fun afterTextChanged(s: Editable?) {

            }
        })
        cb_local_http.setOnCheckedChangeListener { _, it ->
            httpTest.switchHttp(it)
            renameLog()

        }

        // 远程服务配置
        et_ip_http.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                httpTest.serverIp = et_ip_http.text.toString()
            }

            override fun afterTextChanged(s: Editable?) {
            }
        })
        et_port_http.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                try {
                    httpTest.serverPort = et_port_http.text.toString().toInt()
                } catch (e: Exception) {
                }
            }

            override fun afterTextChanged(s: Editable?) {
            }
        })

        cb_http_send_loop.setOnCheckedChangeListener { _, it -> httpTest.send_loop = it }
        bt_http_send.setOnClickListener { httpTest.send(et_text_send.text.toString()) }
    }

    var sb = StringBuilder()
    var index = 0
    override fun appendText(str: String) {
        LogUtil.e("socket_test", str)
        sv_text.post {
            LogSaveManager.instance().logServer(
                Environment.getExternalStorageDirectory().absolutePath + "/test/${logName}.txt",
                LogSaveType.addEnd, 20 * 1024 * 1024
            ).log(str)
            sb.append("$index: ${str}\n\n")
            tv_text.text = sb.toString()
            ++index
            sv_text.post {
                sv_text.fullScroll(ScrollView.FOCUS_DOWN)
            }
            val len = 10 * 1024
            if (sb.length > len) {
                val substring = sb.substring(sb.length - len, sb.length)
                sb.clear()
                sb.append(substring)
            }
        }
    }

    override fun getContext(): Context {
        return applicationContext
    }

    override fun onDestroy() {
        super.onDestroy()
        httpTest.close()
        udpTest.close()
    }
}